package com.bds.btcdc.handler;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;

import com.bds.btcdc.adapter.okex.market.OkexReceiver;
import com.bds.btcdc.model.CoinPairExchanges;
import com.bds.btcdc.service.CoinPairExchangesService;
import com.bds.btcdc.util.Const;
import com.bds.btcdc.util.SpringContextHolder;

public class OKEXSessionHandler extends StompSessionHandlerAdapter {

	private static final Logger logger = LoggerFactory.getLogger(OKEXSessionHandler.class);

	@Override
	public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
		// 查询对冲平台支持的币对
		CoinPairExchangesService exchangesService = SpringContextHolder.getBean(CoinPairExchangesService.class);

		List<CoinPairExchanges> okex_pairs = exchangesService.getPairs("OKEX");

		try {
			new OkexReceiver(session, new URI(Const.OKEX.WS_URL), okex_pairs).connect();

			//
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void handleFrame(StompHeaders headers, Object payload) {
		logger.info("handleFrame");
	}

	@Override
	public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload,
			Throwable exception) {
		logger.info("handleException::" + exception);
	}

	@Override
	public void handleTransportError(StompSession session, Throwable exception) {
		logger.info("OKEX wbsocket 连接关闭,异常信息：" + exception);
		new Thread() {
			@Override
			public void run() {
				try {
					Thread.sleep(Const.RE_CONN_TIME);
					logger.info("OKEX wbsocket 重新建立连接........");
					WebSocketClient client = new StandardWebSocketClient();

					WebSocketStompClient stompClient = new WebSocketStompClient(client);
					stompClient.setMessageConverter(new MappingJackson2MessageConverter());
					OKEXSessionHandler sessionHandler = new OKEXSessionHandler();
					stompClient.connect(Const.WS_URL, sessionHandler);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
}
